package com.example.thirdhomework

import android.os.Bundle
import android.os.Handler
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class FifthActivity : AppCompatActivity() {
    var seconds = 0
    var running = false
    var wasRunning = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_fifth)
        if(savedInstanceState != null){
            seconds = savedInstanceState.getInt("seconds")
            running = savedInstanceState.getBoolean("running")
            wasRunning = savedInstanceState.getBoolean("wasRunning")
        }

        timer()
        val button1 = findViewById<android.widget.Button>(R.id.button1)
        val button2 = findViewById<android.widget.Button>(R.id.button2)
        val button3 = findViewById<android.widget.Button>(R.id.button3)

        button1.setOnClickListener {
            running = true
        }

        button2.setOnClickListener {
            running = false
        }

        button3.setOnClickListener {
            running = false
            seconds = 0
        }
    }



    fun timer (){
        val handler = android.os.Handler()
        val runnable = object : Runnable {
            override fun run() {
                val hours = seconds / 3600
                val minutes = seconds % 3600 / 60
                val secs = seconds % 60
                val time = findViewById<android.widget.TextView>(R.id.textView)
                time.text = String.format("%02d:%02d:%02d", hours, minutes, secs)
                if(running){
                    seconds++
                }
                handler.postDelayed(this, 1000)
            }
        }
        handler.post(runnable)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("seconds", seconds)
        outState.putBoolean("running", running)
        outState.putBoolean("wasRunning", wasRunning)
    }
}